package com.cze.servlet;

import com.cze.service.ProductSerivce;
import com.cze.vo.Product;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@WebServlet("/Product")
@MultipartConfig
public class ProductManageServlet extends HttpServlet {
    ProductSerivce productSerivce = (ProductSerivce) LoderServlet.getBean("productSerivceImpl");

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path;
        if(req.getSession().getAttribute("id")==null){
            path = req.getContextPath()+"/user/login.jsp";
        }else {
            path = req.getContextPath()+"/Product?op=manage&page=0&limit=10";
            req.setCharacterEncoding("utf-8");
            String op = req.getParameter("op"); // 操作

            String serialNumber = req.getParameter("serialNumber");// 系列
            String name = req.getParameter("name"); // 名称
            String brand = req.getParameter("brand");// 品牌
            String model = req.getParameter("model");// 型号
            double price = Double.parseDouble(req.getParameter("price"));// 价格
            String description = req.getParameter("description");// 商品描述
            int productID;          // 商品ID
            String picture;         // 图片
            productID = 0;
            Product product;

            Part part=req.getPart("file");// 获取上传的文件
            try {
                String hname=part.getHeader("content-disposition"); //获取请求的信息
                String root=req.getServletContext().getRealPath("/static/images"); //获取上传文件的目录
                String suffix=hname.substring(hname.lastIndexOf("."), hname.length()-1); //获取文件的后缀
                picture = UUID.randomUUID().toString()+suffix;//生成一个新的不重复文件名
                String filename=root+"\\"+ picture;
                part.write(filename);
            }catch (StringIndexOutOfBoundsException e){
                System.out.println(e.getMessage());
                picture = req.getParameter("tpicture");
            }

            if("add".equals(op)){
                product = new Product(productID, serialNumber , name , brand , model , price , picture , description);
                if(!productSerivce.add(product)){
                    req.setAttribute("info","添加失败");
                    req.getRequestDispatcher("/product/add.jsp").forward(req, resp);
                    return;
                }
            }else if("modify".equals(op)){
                productID = Integer.parseInt(req.getParameter("productID"));
                product = new Product(productID, serialNumber , name , brand , model , price , picture , description);
                req.setAttribute("id", productID);
                if(!productSerivce.modify(product)) {
                    req.setAttribute("info","修改失败");
                    req.setAttribute("op","modify");
                    req.getRequestDispatcher("/product").forward(req, resp);
                    return;
                }
            }
        }
        resp.sendRedirect(path);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = "product/index.jsp";
        String op = req.getParameter("op");
        int id;
        boolean isLogin = req.getSession().getAttribute("id")!=null;

        switch (op){  // 从 Java SE 7 开始，switch 支持字符串 String 类型
            case "page": case "manage":
                int page = Integer.parseInt(req.getParameter("page"));
                int limit = Integer.parseInt(req.getParameter("limit"));
                req.setAttribute("list", productSerivce.getProducts(page,limit));
                req.setAttribute("count", productSerivce.countAll());
                req.setAttribute("page",page);
                break;
            case "delete":
                id = Integer.parseInt(req.getParameter("id"));
                productSerivce.delete(id);
                resp.sendRedirect(req.getHeader("referer"));
                return;
            case "search":
                String keyword = req.getParameter("keyword");
                req.setAttribute("list", productSerivce.search(keyword));
                break;
            case "modify":
                if(isLogin){
                    id = Integer.parseInt(req.getParameter("id"));
                    req.setAttribute("product", productSerivce.findByID(id));
                    path = "product/modify.jsp";
                } else {
                    resp.sendRedirect(req.getContextPath()+"/user/login.jsp");
                    return;
                }
                break;
            case "detail":
                id = Integer.parseInt(req.getParameter("id"));
                req.setAttribute("product", productSerivce.findByID(id));
                path = "product/detail.jsp";
                break;
        }
        if((op.equals("manage")||op.equals("search"))&&isLogin)
            path = "product/manage.jsp";

        req.getRequestDispatcher(path).forward(req, resp);
    }
}
